/**
 * Created by qqli on 5/27/15.
 */
'use strict';

Ctrl.controller('StatistAppNameCtrl', ['$scope', '$http', '$rootScope', 'updateSqcService',
    function ($scope, $http, $rootScope, AppSqc) {
        $rootScope.title = 'Statistics';
        $rootScope.header = 'Search';
        $rootScope.path = "statist";

        $rootScope.activeLi();

        $('.datetimepicker').remove();
        loadStyle(HOST + "styles/build/statist.min.css");
        loadStyle(HOST + "bower_components/bootstrap-datetimepicker/datetimepicker.min.css");
        loadScript(HOST + "bower_components/bootstrap-datetimepicker/datetimepicker.min.js");

        $('footer a').html('Go to Dashboard chart').attr('href', HOST + 'admin/#/dashboard');

        $(window).resize(function () {
            resizeTable(60);
        });
        resizeTable(60);

        // params for url
        $scope.fixParams = {
            type: 1,
            pageNo: 1
        };
        // params for query
        $scope.queryParams = {
            startTime: '',
            endTime: '',
            appName: ''
        };

        /* functions */
        var jqPagination = $('#pagination');
        $scope.queryApp = function (pageNo) {
            if (pageNo) {
                $scope.fixParams.pageNo = pageNo;
            }
            $http.post(HOST + 'statistics/dynamic/' + $scope.fixParams.type + '/'
                + $scope.fixParams.pageNo + '/', $scope.queryParams)
                .success(function (data) {
                    if (data.status === 1) {
                        var _data = data.data;
                        $scope.apps = _data.list;
                        doPagination(jqPagination, _data);

                    } else if (data.status === -1) {
                        lozLogin();
                    }
                });
        };

        /**
         * @param $el
         * @param _data
         * total page
         * pagination(): make pagination
         * jumpToPage(): input and turn to page
         * @type {number}
         */
        function doPagination($el, _data) {
            var totalPage = Math.ceil(_data.total / _data.pageSize);
            if (totalPage <= 1) {
                $el.html('');
                return false;
            }
            pagination($el, _data.pageNo, totalPage, _data.total);
            jumpToPage($el, totalPage, function (i) {
                $scope.fixParams.pageNo = i;
                $scope.queryApp();
            });
        }

        // click page num and turn to page
        function doGotoPage($el) {
            $el.on('click', '.goto', function () {
                $scope.fixParams.pageNo = $(this).data('page');
                $scope.queryApp();
                return false;
            });
        }

        doGotoPage(jqPagination);

        // init
        $scope.queryApp();
    }]);